//
//  MyschemeViewController.m
//  liangyi
//
//  Created by 张水 on 16/12/20.
//  Copyright © 2016年 yswh. All rights reserved.
//

#import "MyschemeViewController.h"
#import "MyschemeCell.h"
#import "AppHeader.h"
#import "MyschemeHeadView.h"
#import "SchemeModel.h"
#import "ZXVideo.h"
#import "VideoPlayViewController.h"
#import "DetailVideoViewController.h"
@interface MyschemeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView  *tableView;

@property(nonatomic,strong) MyschemeHeadView *headView;

@property(nonatomic,strong) NSMutableArray  *stageArr;

@property(nonatomic,strong) NSMutableArray *dataArr;

@property(nonatomic,strong) GFCalendarView *calendar;

@property(nonatomic,strong) UIView  *backView;

@property(nonatomic,copy)NSString *operationTime;

@property(nonatomic,copy)NSString *pid;

@property(nonatomic,copy)NSString *backtime;

@end

@implementation MyschemeViewController

static NSString *SchemeID = @"SchemeID";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的方案";
    self.view.backgroundColor = [UIColor whiteColor];
    self.stageArr = [NSMutableArray array];
    self.dataArr = [NSMutableArray array];
    [self setupNavigation];
    [self initUI];
    
 
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
      [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(JumpToDetailVideoViewController:) name:@"JumpToDetailVideoViewController" object:nil];
    [self getMyschemeData];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)setupNavigation{
    
    
    
//    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightButton.frame = CGRectMake(0, 0, 100, 25);
//    [rightButton setTitle:@"修改方案" forState:UIControlStateNormal];
//    [rightButton addTarget:self action:@selector(ModeiTimeAction) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    
}
-(void)initUI {
    
    self.headView = [[MyschemeHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 470)];
    [self.headView.BeginTrain addTarget:self action:@selector(beginTrain) forControlEvents:UIControlEventTouchUpInside];
    [self.headView.ModeiScheme addTarget:self action:@selector(ModeiTimeAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = YES;
    [CommonMethod hiddleExtendCellFromTableview:_tableView];
    self.tableView.tableHeaderView = self.headView;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MyschemeCell class] forCellReuseIdentifier:SchemeID];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.backView.backgroundColor = [UIColor blackColor];
    self.backView.alpha = 0.4;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeSubViews)];
    [self.backView addGestureRecognizer:tapGesture];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.stageArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyschemeCell *cell = [tableView dequeueReusableCellWithIdentifier:SchemeID forIndexPath:indexPath];
    if (!cell) {
       cell = [cell initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:SchemeID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.MyModel = self.stageArr[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(void)JumpToDetailVideoViewController:(NSNotification *)nsotify{
    NSDictionary *dict = nsotify.userInfo;
    NSString *playUrl = dict[@"videoAddress"];
    NSString *title = dict[@"title"];
    NSString *rid = dict[@"rid"];
    ZFPlayerModel *playerModel = [[ZFPlayerModel alloc]init];
    playerModel.videoURL = [NSURL URLWithString:playUrl];
    playerModel.title = title;
    DetailVideoViewController *vc = [[DetailVideoViewController alloc] init];
    vc.titles = title;
    vc.videoUrl = playUrl;
    vc.rid = rid;
    [self.navigationController pushViewController:vc animated:YES];

}

-(void)beginTrain{
    VideoPlayViewController  *vc = [VideoPlayViewController new];
    vc.dataArr = self.dataArr;
    if (self.dataArr.count == 0){
        [self.navigationController popToRootViewControllerAnimated:YES];
        return ;
    }
    recoveriesModel *model = self.dataArr[0];
    vc.titles = model.title;
    vc.videoUrl =  model.videoAddress;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)ModeiTimeAction{
    
    if (self.stageArr.count == 0){
        [CustomProgressHUD showSuccessWithStatus:@"您还没有定制方案"];
        return ;
    }
    
    [[[UIAlertView alloc]initWithTitle:@"确定修改方案么?" message:@"请您严格按照医师的指导执行您的训练计划，如若随意修改，可能会出现一些问题，请您慎重选择。" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil] show ];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0){

    }
    if (buttonIndex == 1){
        
        NSString *url = [BASEURL stringByAppendingString:kURL_delScheme];
        NSDictionary *dict = @{@"pid":self.pid};
        NSLog(@"%@",dict);
        NSString *jsonString = [NSString dictionaryToJson:dict];
        NSString *AESString = [NSString AES128Encrypt:jsonString];
        NSDictionary *parameters = @{@"parameters":AESString,
                                     @"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
        [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
            NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
            NSInteger code = network.code.integerValue;
            NSLog(@"%@",network.dataObject);
            if (code == 0){
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                [CustomProgressHUD showErrorWithStatus:network.errorDescription];
            }
        } failure:^(id error) {
            [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
        }];
        
    
    }
}

-(void)removeSubViews{
    [self.calendar removeFromSuperview];
    [self.backView removeFromSuperview];
}
-(void)getMyschemeData{
    NSString *url = [BASEURL stringByAppendingString:kURL_MyPlain];
    NSDictionary *dict = @{@"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:dict success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            
            
            SchemeModel *allData = [SchemeModel mj_objectWithKeyValues:network.dataObject];
            [self.stageArr removeAllObjects];
            [self.stageArr addObjectsFromArray:allData.stageList];
            self.stageArr =  [MyschemeModel mj_objectArrayWithKeyValuesArray:self.stageArr];
            
            
            PlanModel *model = [PlanModel mj_objectWithKeyValues:allData.plan];
            self.pid = model.id;
            self.backtime = [NSString timeWithTimeIntervalString:model.operationTime];
            NSLog(@"%@",self.backtime);
            
            [self.headView.ModeiTime setTitle:[NSString stringWithFormat:@"(手术时间:%@)",self.backtime] forState:UIControlStateNormal];
            
            [self.tableView reloadData];
            StageModel *stage = [StageModel mj_objectWithKeyValues:allData.stage];
            if (stage == nil){
                self.tableView.tableHeaderView = nil;
                [CustomProgressHUD showSuccessWithStatus:@"当前阶段没有训练内容,请您休息一下吧!"];
                return ;
            }
            [self.headView loadMySchemeData:stage];
            
            [self.dataArr removeAllObjects];
            [self.dataArr addObjectsFromArray:stage.recoveries];
            self.dataArr = [recoveriesModel mj_objectArrayWithKeyValuesArray:self.dataArr];
            
            self.headView.desLable.text = @"您已经定制了您的康复计划方案，请您先点击开始训练按钮完成你选择的康复计划。";
        }else{
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
            self.headView.hidden = YES;
            
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];

}
-(void)ModefiTime{
    NSString *url = [BASEURL stringByAppendingString:kURL_upDateTime];
    NSDictionary *dict = @{@"operationTime":self.operationTime,
                           @"pid":self.pid};
    NSLog(@"%@",dict);
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString,
                                 @"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            [CustomProgressHUD   showSuccessWithStatus:@"手术时间修改成功"];
        }
    } failure:^(id error) {
        
    }];
    
    
}
- (NSString *)timeGOTimeIntervalString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd日"];
    
//    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
@end
